const express=require('express');
const app =express();
const router=express.Router();
var bcrypt=require('bcryptjs')
var gravatar=require('gravatar')
var jwt =require('jsonwebtoken')
const key =require('../../config/keys')
const passport =require('passport')
const mongoose =require('mongoose');
const Profile = require('../../models/Profile');

router.get('/test',(req,res)=>{
    console.log('test成功了')
    res.json({msg:"test成功了"})
})

router.post('/add',passport.authenticate('jwt',{session:false}),(req,res)=>{
    //判断数据是否存在，如果不存在，新建 
    const profileFidlds={};
    console.log(req.body)
    console.log(222,req.user);

    profileFidlds.userid=req.user._id;
    if(req.body.type){profileFidlds.type=req.body.type}
    if(req.body.descript){profileFidlds.descript=req.body.descript}
    if(req.body.income){profileFidlds.income=req.body.income}
    if(req.body.expend){profileFidlds.expend=req.body.expend}
    if(req.body.cash){profileFidlds.cash=req.body.cash}
    if(req.body.remark){profileFidlds.remark=req.body.remark}

    //存储数据
    new Profile(profileFidlds).save().then(Profile=>{
        res.json(Profile)
    }).catch((err)=>{
        console.log(err)
    })
})
//查看所有信息
router.get('/',passport.authenticate('jwt',{session:false}),(req,res)=>{
    Profile.find().then(Profile=>{
        if(!Profile){
            return res.status(400).json('查不到数据')
                }
                res.json(Profile)
    }).catch(err=>
        res.status(400).json(err)
    )
})

//查单条信息
router.get('/:id',
passport.authenticate('jwt',{session:false}),
(req,res)=>{
 
 //   console.log("_id="+req.params.id)
    Profile.findOne({_id:req.params.id})
    .then(Profile=>{
        if(!Profile){
            return res.status(400).json('你查不到内容')
        }
        res.json(Profile)
    }).catch(err=>{res.status(400).json(err)})
}
)

router.post('/edit/:id',
passport.authenticate('jwt',{session:false}),
(req,res)=>{
    //判断是数据是否存在，如果不存在的情况下，新建
    const profileFields={}
    if(req.body.type){profileFields.type = req.body.type}
    if(req.body.descript){profileFields.descript = req.body.descript}
    if(req.body.income){profileFields.income = req.body.income}
    if(req.body.expend){profileFields.expend = req.body.expend}
    if(req.body.cash){profileFields.cash = req.body.cash}
    if(req.body.remark){profileFields.remark = req.body.remark}
    //更新数据，先找到此ID，改变，更新数据
    Profile.findOneAndUpdate(
        {_id:req.params.id},{$set:profileFields},
        {new:true}
    ).then(profile=>res.json(profile))

}
)
router.get('/delete/:id',
passport.authenticate('jwt',{session:false}),
(req,res)=>{
    Profile.findByIdAndRemove({_id:req.params.id})
    .then(profile=>{
        console.log(8,Profile);
        res.json("删除成功！！")

    }).catch(err=>res.status(400).json('删除失败！！'))
}
)


module.exports=router;